package com.wyw.hemerocallis.service.comunication;

import com.alibaba.fastjson.JSON;
import com.wyw.hemerocallis.constant.CommonConstant;
import com.wyw.hemerocallis.vo.JwtToken;
import com.wyw.hemerocallis.vo.UsernameAndPassword;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 使用RestTemplate实现微服务通信
 *
 * @author Mr Wu    yewen.wu.china@gmail.com
 * <p>
 * Update History:
 * Author        Time            Content
 */
@Slf4j
@Service
public class UserRestTemplateService {

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    /**
     * url写死
     */
    public JwtToken getTokenFromAuthorityService(UsernameAndPassword usernameAndPassword) {
        String requestUrl = "http://127.0.0.1:7000/hemerocallis-authority-center" +
                "/authority/token";
        log.info("RestTemplate request url and body:[{}],[{}]",
                requestUrl, JSON.toJSONString(usernameAndPassword));

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        return new RestTemplate().postForObject(
                requestUrl,
                new HttpEntity<>(JSON.toJSONString(usernameAndPassword), headers),
                JwtToken.class
        );
    }

    /**
     * 带有负载均衡请求
     */
    public JwtToken getTokenFromAuthorityServiceWithLoadBalancer(
            UsernameAndPassword usernameAndPassword) {
        //通过注册中心获取服务的信息
        ServiceInstance serviceInstance = loadBalancerClient.choose(
                CommonConstant.AUTHORITY_CENTER_SERVICE_ID
        );

        log.info("Nacos Client Info: [{}], [{}], [{}]",
                serviceInstance.getServiceId(), serviceInstance.getInstanceId(),
                JSON.toJSONString(serviceInstance.getMetadata()));

        String requestUrl = String.format(
                "http://%s:%s/hemerocallis-authority-center/authority/token",
                serviceInstance.getHost(),
                serviceInstance.getPort()
        );
        log.info("login request url and body:[{}],[{}]", requestUrl,
                JSON.toJSONString(usernameAndPassword));

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        return new RestTemplate().postForObject(
                requestUrl,
                new HttpEntity<>(JSON.toJSONString(usernameAndPassword), headers),
                JwtToken.class
        );
    }


}
